package com.htd.base.common.exception;

import com.htd.base.common.ResultCode;
import com.htd.base.common.ResultInfo;
import com.htd.base.modules.translate.enumeration.LangCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.MethodParameter;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.text.MessageFormat;
import java.util.Locale;

/**
 * 異常處理器
 *
 * @author Wangqi
 */
@RestControllerAdvice(basePackages = {"com.htd.base.modules"})
public class BaseExceptionHandler implements ResponseBodyAdvice<Object> {
	private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(BaseExceptionHandler.class);

	@Autowired
	private MessageSource messageSource;

	/**
	 * 攔截自定義的異常
	 */
	@ExceptionHandler(BaseException.class)
	public ResultInfo handleAppException(BaseException e) {
		LOGGER.warn(e.getMessage(), e);
		return ResultInfo.build(ResultCode.ERROR.getCode(), ResultCode.NOT_FOUND.getName(), getLocaleMessage(e.getCode(), e.getParams()),null,null);
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public ResultInfo handlerNoFoundException(Exception e) {
		LOGGER.error("框架攔截異常信息！",e);
		return ResultInfo.build(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getName(),getLocaleMessage(ResultCode.NOT_FOUND.getName(), null),null,null);
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public ResultInfo handleDuplicateKeyException(DuplicateKeyException e){
		LOGGER.error("框架攔截異常信息！",e);
		return ResultInfo.build(ResultCode.DATA_EXIST.getCode(), ResultCode.DATA_EXIST.getName(), getLocaleMessage(ResultCode.DATA_EXIST.getName(), null),null,null);
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResultInfo handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
		LOGGER.error("框架攔截異常信息！",e);
		BindingResult bindingResult = e.getBindingResult();
		StringBuilder sb = new StringBuilder("參數錯誤:");
		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
		}
		String msg = sb.toString();
		return ResultInfo.build(ResultCode.PARAM_ERROR.getCode(), ResultCode.PARAM_ERROR.getName(), msg,null,null);
	}

	/**
	 * 處理其他拋出的異常
	 */
	@ExceptionHandler(Exception.class)
	public ResultInfo handleException(Exception e) {
		LOGGER.error("框架攔截異常信息！",e);
		return ResultInfo.build(ResultCode.ERROR.getCode(), ResultCode.ERROR.getName(), getLocaleMessage(ResultCode.ERROR.getName(), null),null,null);
	}
	/**
	 * 獲取國際化異常資訊
	 */
	private String getLocaleMessage(String code, Object[] params) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String languageTypeCode =request.getHeader("languageTypeCode");
		// 默認英語
		Locale locale = new Locale(LangCodeEnum.EN.getLangCode());
		if (StringUtils.isNotEmpty(languageTypeCode)) {
			locale = new Locale(languageTypeCode);
		}
		String pattern = messageSource.getMessage(code, null, locale);
		if (StringUtils.isNotEmpty(pattern)) {
			return MessageFormat.format(pattern, params);
		} else {
			return "";
		}
	}

	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response)  {
		ResultInfo<Object> resultInfo = null;
		if (body instanceof ResultInfo) {
			resultInfo = (ResultInfo)body;
			resultInfo.setResultCode(((ResultInfo) body).getResultCode());
			if (StringUtils.isNotEmpty(((ResultInfo) body).getMessageCode())) {
				resultInfo.setResultMessage(getLocaleMessage(((ResultInfo) body).getMessageCode(), null));
			} else {
				resultInfo.setResultMessage(getLocaleMessage(ResultCode.SUCCESS.getName(), null));
			}
			return resultInfo;
		} else {
			resultInfo = new ResultInfo<Object>();
			resultInfo.setResultCode(ResultCode.SUCCESS.getCode());
			resultInfo.setResultMessage(getLocaleMessage(ResultCode.SUCCESS.getName(), null));
			resultInfo.setBody(body);
		}
		return resultInfo;
	}
}
